<?php
namespace app\admin\validate;
use think\Validate;
use app\admin\model\AdminUser;
class Login extends Validate
{
	// 正则列
	protected $regex =
	[
		'switch' => '(open)|(shut)',
	];
	// 规则列
	protected $rule =
	[
		'username'	=>	'require|alphaNum|length:5,24',
		'password'	=>	'require|length:6,24',
		'captcha'	=>	'require|alphaNum|length:4',
		'keep'		=>	'require|regex:switch',
		'agreement'	=>	'require|regex:switch',
		'loginsql'	=>	'require|regex:switch|checkAdminDb',
		'oauth2'	=>	'require|regex:switch',
	];
	// 消息列
	protected $message =
	[
		'username.require'		=>	'Username_Must_Input',
		'username.alphaNum'		=>	'Username_Format_Error',
		'username.length'		=>	'Username_Length_Exceed',
		'password.require'		=>	'Password_must_Input',
		'password.length'		=>	'Password_Length_Exceed',
		'captcha.require'		=>	'Captcha_Must_Input',
		'captcha.alphaNum'		=>	'Captcha_Format_Error',
		'captcha.length'		=>	'Captcha_Length_Exceed',
		'keep.require'			=>	'Remember_Must_Input',
		'keep.regex'			=>	'Remember_Format_Error',
		'agreement.require'		=>	'Agreement_Must_Input',
		'agreement.regex'		=>	'Agreement_Format_Error',
		'loginsql.require'		=>	'Loginsql_Must_Input',
		'loginsql.regex'		=>	'Loginsql_Format_Error',
		'loginsql.checkAdminDb'	=>	false,
		'oauth2.require'		=>	'Access_Token_Not_Empty',
		'oauth2.regex'			=>	'Access_Token_Request_Format_Error',
	];
	// 场景列
	protected $scene =
	[
		'login'		=>	['username','password','keep','agreement','captcha','oauth2'],
		'logindb'	=>	['username','loginsql'],
	];

	

	/**
	 * checkAdminDb 进行用户检验数据检测
	 * @param  string $value 传入检验的字符
	 * @param  string $rule  传入检测的规则
	 * @param  array $data  整个数据内容传入
	 * @return string        错误时返回一个字符串
	 * @return bool        正确时返回一个bool的真值
	 */
	protected function checkAdminDb($value,$rule,$data=[])
	{
		$password2 = passRule($data['password']);
		// 开关是否被打开
		if ($value === 'shut') return true;
		else
		{
			$user = AdminUser::where('username', $data['username'])->where('status','=',1)->field('password,status')->find();
			if (empty($user)) return 'Username_Or_Password_Error';
			$password2 = passRule($data['password']);
			if ($user['password'] !== $password2) return 'Username_Or_Password_Error';
			if ($user['status'] != 1) return 'Username_Forbid_Login';
			return true;
		}
	}
}